from django.contrib.auth.hashers import check_password
from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from users.models import User


class QQUserSerializer(serializers.Serializer):
    """QQ登录创建用户序列化器"""
    openid = serializers.CharField(label='openid', write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$',
                                    write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    password = serializers.CharField(label='密码', max_length=20, min_length=8,
                                     write_only=True)

    def validate(self, attrs):
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']
        password = attrs['password']

        redis_dict = get_redis_connection('sms_codes')
        real_sms_code = redis_dict.get('sms_%s' % mobile)

        if not real_sms_code:
            raise serializers.ValidationError({'message': '短信验证码无效'})
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError({'message': '短信验证码输入错误'})
        # 根据手机号查询用户,查询不到的话就创建一个新的用户
        try:
            user = User.objects.get(mobile=mobile)
        except:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile
            )
        else:
            # 如果用户存在,则校验密码是否正确
            if not user.check_password(password):
                raise serializers.ValidationError({'message': '用户密码错误'})

        # 将认证的用户放进去校验字典中,绑定关联时用到
        attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 获取校验的用户
        user = validated_data.get('user')
        openid = validated_data.get('openid')

        # 绑定openid和美多用户,新增一条表数据
        OAuthQQUser.objects.create(
            openid=openid,
            user=user
        )
        return user  # 返回美多用户对象















